export default {
  namespaced: true,
  state() {
    return {
      cartList: JSON.parse(uni.getStorageSync('cart') || '[]'),
      show: false,
      cartIndex: 0,
      dropIdx: 0,
      num: 1,
      loginShow:false
    }
  },
  actions: {},
  mutations: {
    addCart(state, obj) {
      let res = state.cartList.find(item => item.id === obj.id)
      res ? res.goods_count++ : state.cartList.push(obj)
      uni.setStorageSync('cart', JSON.stringify(state.cartList))
    },
    cartCheckMut(state, id) {
      state.cartList.forEach(item => {
        if (item.id == id) {
          item.isCheck = !item.isCheck
        }
      })
      uni.setStorageSync('cart', JSON.stringify(state.cartList))
    },
    cartAllCheckMut(state, isAll) {
      state.cartList.forEach(item => {
        item.isCheck = !isAll
      })
    },
    handleDelCart(state, id) {
      state.cartList = state.cartList.filter(item => {
        return item.id !== id
      })
      uni.setStorageSync('cart', JSON.stringify(state.cartList))
    },
    changeShow(state, isShow) {
      state.show = isShow
    },
    changeDropIdx(state, idx) {
      state.dropIdx = idx
    },
    changeCartIndex(state, index) {
      state.cartIndex = index
    },
    changeNum(state, val) {
      state.num = val
    },
    saveEditValue(state) {
      const {
        cartIndex,
        dropIdx,
        num
      } = state
      // 购物车列表无法立即更新
      // state.cartList[cartIndex] = {
      //   ...state.cartList[cartIndex],
      //   goods_count: num,
      //   idx: dropIdx
      // }
      state.cartList[cartIndex].goods_count = num
      state.cartList[cartIndex].idx = dropIdx
      uni.setStorageSync('cart', JSON.stringify(state.cartList))
    },
    changeLoginShow(state,isShow) {
      state.loginShow = isShow
    },
    cartRemove(state) {
      state.cartList = state.cartList.filter((item) => {
        return item.isCheck === false
      })
      uni.setStorageSync('cart', JSON.stringify(state.cartList))
    }

  },
  getters: {
    allInfo(state) {
      let allPrice = 0
      let checkNum = 0
      let allNum = state.cartList.reduce((count,item) => {
        return count + item.goods_count
      },0)
      //[].every()返回为true
      // console.log([].every(item => {
      //   return item.id ==1
      // }));
      let allCheck = state.cartList.length > 0 && state.cartList.every(item => {
        return item.isCheck == true
      }) ? true : false
      state.cartList.forEach((item) => {
        if(item.isCheck) {
          checkNum += item.goods_count
        }
      })
      state.cartList.forEach(item => {
        if (item.isCheck) {
          allPrice += Number(item.list[item.idx]?.pprice) * item.goods_count
        }
      })
      return {
        checkNum,
        allNum,
        allPrice:allPrice.toFixed(2),
        allCheck
      }
    },
    checkGoods(state) {
      return state.cartList.filter((item) => {
        return item.isCheck === true
      })
    }
  }
}
